package com.web.utils;
/**
 * date:2012-9-14 上午08:59:42
 *  缩略图实现，将图片(jpg、bmp、png、gif等等)真实的变成想要的大小 
 */  
  
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.awt.image.CropImageFilter;
import java.awt.image.FilteredImageSource;
import java.awt.image.ImageFilter;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;

import javax.imageio.ImageIO;
  
/******************************************************************************* 
 * 缩略图类（通用） 本java类能将jpg、bmp、png、gif图片文件，进行等比或非等比的大小转换。 具体使用方法 
 * compressPic(大图片路径,生成小图片路径,大图片文件名,生成小图片文名,生成小图片宽度,生成小图片高度,是否等比缩放(默认为true)) 
 */  
 public class ImagesResize {   
     private File file = null; // 文件对象   
     private InputStream input;
     private int outputWidth;  // 默认输出图片宽  
     private int outputHeight; // 默认输出图片高  
     private boolean proportion = true; // 是否等比缩放标记(默认为等比缩放) 
     
     
     public ImagesResize() { // 初始化变量  
         outputWidth = 200;   
         outputHeight = 200;   
     }   
     public void setOutputWidth(int outputWidth) {  
         this.outputWidth = outputWidth;   
     }   
     public void setOutputHeight(int outputHeight) {   
         this.outputHeight = outputHeight;   
     }   
     public void setWidthAndHeight(int width, int height) {   
         this.outputWidth = width;  
         this.outputHeight = height;   
     }   
     
     public void setProportion(boolean proportion) {   
         this.proportion = proportion;   
     }
     /*  
      * 获得图片大小  
      * 传入参数 String path ：图片路径  
      */   
     public long getPicSize(String path) {   
         file = new File(path);   
         return file.length();   
     }  
    
 	
 	 public byte[] imgCreate(InputStream input,int oh,int ow,int x,int y,int towidth,int toheight) {   
         try {   
             Image img = ImageIO.read(input); 
             // 判断图片格式是否正确   
             if (img.getWidth(null) == -1) {  
                 return null;   
             } else {   
                ImageFilter cropFilter = new CropImageFilter(x, y,ow, oh);   
				img = Toolkit.getDefaultToolkit().createImage(new FilteredImageSource(img.getSource(), cropFilter));  
                BufferedImage tag = new BufferedImage(towidth, toheight, BufferedImage.TYPE_USHORT_565_RGB);  
                
                tag.getGraphics().drawImage(img.getScaledInstance(towidth, toheight, Image.SCALE_SMOOTH), 0, 0, null);  
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                ImageIO.write(tag, "jpg",out);
               return out.toByteArray();
              
             }   
         } catch (IOException ex) {   
             ex.printStackTrace();   
             return null;   
         }
           
    }
     // 图片处理   
     public byte[] compressPic() {   
         try {   
             Image img = ImageIO.read(input); 
             // 判断图片格式是否正确   
             if (img.getWidth(null) == -1) {  
                 return null;   
             } else {   
                 int newWidth; int newHeight;   
                 // 判断是否是等比缩放   
                 if (proportion) {   
                     // 为等比缩放计算输出的图片宽度及高度   
                     double rate1 = ((double) img.getWidth(null)) / (double) outputWidth + 0.1;   
                     double rate2 = ((double) img.getHeight(null)) / (double) outputHeight + 0.1;   
                     // 根据缩放比率大的进行缩放控制   
                     double rate = rate1 > rate2 ? rate1 : rate2;   
                     newWidth = (int) (((double) img.getWidth(null)) / rate);   
                     newHeight = (int) (((double) img.getHeight(null)) / rate);   
                 } else {   
                     newWidth = outputWidth; // 输出的图片宽度   
                     newHeight = outputHeight; // 输出的图片高度   
                 }   
                BufferedImage tag = new BufferedImage((int) newWidth, (int) newHeight, BufferedImage.TYPE_USHORT_565_RGB);   
                  
                /* 
                 * Image.SCALE_SMOOTH 的缩略算法 生成缩略图片的平滑度的 
                 * 优先级比速度高 生成的图片质量比较好 但速度慢 
                 */   
                tag.getGraphics().drawImage(img.getScaledInstance(newWidth, newHeight, Image.SCALE_SMOOTH), 0, 0, null);  
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                ImageIO.write(tag, "jpg",out);
               return out.toByteArray();
              
             }   
         } catch (IOException ex) {   
             ex.printStackTrace();   
             return null;   
         }
           
    }   
     
    /* public void saveImageUsingJPGWithQuality(BufferedImage image,  
             String filePath, float quality) throws Exception {  
    	 int newWidth ,newHeight;
    	 if(proportion){
    		 double rate1 = ((double) image.getWidth(null)) / (double) outputWidth + 0.1;   
    		 double rate2 = ((double) image.getHeight(null)) / (double) outputHeight + 0.1;   
    		 // 根据缩放比率大的进行缩放控制   
    		 double rate = rate1 > rate2 ? rate1 : rate2;   
    		 newWidth = (int) (((double) image.getWidth(null)) / rate);   
    		 newHeight = (int) (((double) image.getHeight(null)) / rate);   
    	 }else{
    		 newWidth =outputWidth;   
    		 newHeight = outputHeight;   
    	 }
         
         BufferedImage newBufferedImage = new BufferedImage(newWidth,newHeight, BufferedImage.TYPE_USHORT_565_RGB);//4  
         newBufferedImage.getGraphics().drawImage(image.getScaledInstance(newWidth, newHeight, Image.SCALE_SMOOTH), 0, 0, null);  
   
         Iterator<ImageWriter> iter = ImageIO  
                 .getImageWritersByFormatName("jpeg");  
   
         ImageWriter imageWriter = iter.next();  
         ImageWriteParam iwp = imageWriter.getDefaultWriteParam();  
   
         iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);  
         iwp.setCompressionQuality(quality);  
   
         File file = new File(filePath);  
         FileImageOutputStream fileImageOutput = new FileImageOutputStream(file);  
         imageWriter.setOutput(fileImageOutput);  
         IIOImage iio_image = new IIOImage(newBufferedImage, null, null);  
         imageWriter.write(null, iio_image, iwp);  
         imageWriter.dispose(); 
         
         
         ByteArrayOutputStream out = new ByteArrayOutputStream();
         ImageIO.write(newBufferedImage, "jpg",file);//new File(outputDir + outputFileName)
     } */
     
  /**
   * 
   * @param input 图的输入图流
   * @param outputDir 目录
   * @param outputFileName 文件名
   * @param width 
   * @param height
   * @param gp 是否等比例缩放
   * @return
   */
    public byte[] compressPic (InputStream input, int width, int height, boolean gp) {   
        // 图的输入图流   
        this.input = input;   
        this.outputHeight=height;
        this.outputWidth=width;
        this.proportion=gp;
        return compressPic();   
    } 
   
      
    // main测试   
    // compressPic(大图片路径,生成小图片路径,大图片文件名,生成小图片文名,生成小图片宽度,生成小图片高度,是否等比缩放(默认为true))  
    public static void main(String[] arg) throws Exception {   
    	//ImagesResize mypic = new ImagesResize();   
//        logger.info("输入的图片大小：" + mypic.getPicSize("http://10.10.9.35:8080/group1/M00/00/00/CgoJJFPrQHmAHQenABAYd7DbULQ120.jpg")/1024 + "KB");   
//      InputStream input=new FileInputStream(new File("E:\\IMG_20130930_205840.jpg"));
//        for (int i = 0; i < 1; i++) {   
//            int start = (int) System.currentTimeMillis();   // 开始时间   
//           // mypic.compressPic(input, "E:\\", "r111.jpg", 200, 200, true);   
//            int end = (int) System.currentTimeMillis(); // 结束时间   
//            int re = end-start; // 但图片生成处理时间   
//           // count += re; logger.info("第" + (i+1) + "张图片压缩处理使用了: " + re + "毫秒");   
//           // logger.info("输出的图片大小：" + mypic.getPicSize("d:\\test\\r1"+i+".jpg")/1024 + "KB");   
//            logger.info("总共用了：" + re+ "毫秒");   
//        }  
    //	BufferedImage bi=ImageIO.read(new File("E:\\5524146_120747204114_2.jpg"));
    	
    	//mypic.saveImageUsingJPGWithQuality(bi,"E:\\eew.jpg",0.8f);
    }   
 } 